<?php

class Admin_Model_Term_Mapper extends Admin_Model_MapperAbstract {
	protected $db;
	
	public function __construct($db) {
		parent::__construct($db);
		$this->db = $db;
		$this->setDbTable(new Admin_Model_Term_DbTable(array(Admin_Model_Term_DbTable::ADAPTER => $db)));
	}
	
	/**
	 * 
	 * @param Admin_Model_Term_Term $model
	 * @return mixed
	 */
	public function save(Admin_Model_Term_Term $model) {
		$Data = array(
			'ID' => $model->getId(),
			'Name' => $model->getName(),
			'Value' => $model->getValue(),
			'Type' => $model->getType(),
			
		);

		$Id = parent::save($Data);
		
		$Meta = new Admin_Model_Term_MetaData($this->db);
		$ParentId = $model->getParentId();
		if (!is_array($ParentId)) {
			$ParentId = array($ParentId);
		}
		
		foreach ($ParentId as $v) {
			$Meta->insert(array(
				'TermID' => $Id,
				'ParentID' => $v,
				'Order' => 0
			));
		}
		
		return $Id;
	}

	/**
	 * 
	 * @param type $id
	 * @return \Admin_Model_Term_Term
	 */
	public function find($id) {
		$Result = parent::find($id);
		if (null === $Result) {
			return;
		}

		$Term = new Admin_Model_Term_Term();
		$Term->setId($Result->ID)
				->setName($Result->Name)
				->setValue($Result->Value)
				->setType($Result->Type);

		return $Term;
	}
	
	protected function parseSelect($condition = array(), $order = null) {
		$Select = $this->getDbTable()->select()->setIntegrityCheck(FALSE)->from($this->getDbTable()->info(Zend_Db_Table_Abstract::NAME));//->where($condition['where'], $condition['value'], $condition['type'])->order($order);
		$Select->joinLeft(Admin_Model_Term_MetaData::getTableName(), 'ID = TermID');
		
		if (is_array($condition)) {
			foreach ($condition as $v) {
				if (is_array($v)) {
					$Select->where($v['where'], $v['value'], $v['type']);
				}
			}
		}
		//var_dump($Select->assemble());
		//exit();
		return $Select;
	}
	
	/**
	 * 
	 * @return array
	 */
	public function fetchAll($where = null, $order = null, $count = null, $offset = null) {
		$Rows = parent::fetchAll($where, $order, $count, $offset);
		$Posts = array();
		foreach ($Rows as $Row) {
			$Post = new Admin_Model_Term_Term();
			$Post->setId($Row->ID)
				->setName($Row->Name)
				->setValue($Row->Value)
				->setType($Row->Type);
		}
		
		return $Posts;
	}
}
